from flask import Blueprint, redirect, url_for, flash, render_template
from flask_login import login_user, current_user, logout_user, login_required
from app.models import User, Crawler, Record, Subscribe
from app.forms import LoginForm, ChangePassword, RegisterForm
from app.extensions import db
from app.utils import redirect_back

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/')
@login_required
def index():
    return render_template('auth/index.html')


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('auth.index'))
    form = LoginForm()
    if form.validate_on_submit():
        email = form.email.data
        password = form.password.data
        remember = form.remember.data
        user = User.query.filter_by(email=email).first()
        if user:
            if email == user.email and user.validate_password(password):
                login_user(user, remember)
                return redirect(url_for('auth.index'))
            flash('密码或用户名错误', 'warning')
        else:
            flash('用户名不存在！请输入正确的用户名或邮箱！', 'warning')
    return render_template('auth/login.html', form=form)


@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('auth.index'))

    form = RegisterForm()
    if form.validate_on_submit():
        email = form.email.data.lower()
        password = form.password.data
        user = User(email=email)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)


@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('成功退出账户', 'info')
    return redirect_back()


@auth_bp.route('change_pw', methods=['GET', 'POST'])
@login_required
def change_password():
    form = ChangePassword()
    if form.validate_on_submit():
        if current_user.validate_password(form.old_password.data):
            current_user.set_password(form.new_password.data)
            db.session.commit()
            flash('密码修改成功！', 'success')
            return redirect(url_for('auth.index'))
        else:
            flash('旧密码错误', 'warning')
    return render_template('auth/change_password.html', form=form)

